/**=========================================================
 * Module: main.js
 * Main Application Controller
 =========================================================*/

App.controller('AppController',
    ['$rootScope', '$scope', '$state', '$translate', '$window', '$localStorage', '$timeout', '$http', '$transitions',
     'tmhDynamicLocale', 'i18nService', 'toggleStateService', 'colors', 'browser', 'cfpLoadingBar', 'HttpUtils', 'Utils', 'toaster', 'ngDialog',
    function($rootScope, $scope, $state, $translate, $window, $localStorage, $timeout, $http, $transitions,
             tmhDynamicLocale,i18nService, toggle, colors, browser, cfpLoadingBar, httpUtils, utils, toaster, ngDialog) {
        "use strict";

        // Setup the layout mode
        $rootScope.app.layout.horizontal = ( $rootScope.$stateParams.layout == 'app-h') ;

        //log event
        $transitions.onSuccess({}, function(transition) {
            httpUtils.post('/sysUtil/logVisitMenu',{state: transition.to().name});
        });

        $transitions.onSuccess({}, function(transition) {
            // display new view from top
            $window.scrollTo(0, 0);
            if (!utils.isEmpty($scope.userMenus[transition.to().name])){
                setCurrentTitle(transition.to().name);
            }
        });

        $transitions.onError({}, function(transition) {
            console.log(transition);
        });
    
        $rootScope.pageTitle = function() {
            var title = $rootScope.app.name;
            document.title = title;
            return title; 
        };
        
        // Allows to use branding color with interpolation
        // {{ colorByName('primary') }}
        $scope.colorByName = colors.byName;
   
//==============================================offsidebar-information====================================================    

 
//==============================================offsidebar-setting====================================================
        // iPad may presents ghost click issues
        // if( ! browser.ipad )
        // FastClick.attach(document.body);

        // Close submenu when sidebar change from collapsed to normal
        $rootScope.$watch('app.layout.isCollapsed', function(newValue, oldValue) {
            if( newValue === false )
                $rootScope.$broadcast('closeSidebarMenu');
        });

        // Restore layout settings
        if( angular.isDefined($localStorage.layout) )
            $scope.app.layout = $localStorage.layout;
        else
            $localStorage.layout = $scope.app.layout;

        $rootScope.$watch("app.layout", function () {
            $localStorage.layout = $scope.app.layout;
        }, true);

        $scope.language = {
            // list of available languages
            available: {
                'en':       'English',
                'zh':       'Chinese'
            },
            selected: 'en',
            // display always the current ui language
            init: function () {
                var proposedLanguage = $translate.proposedLanguage() || $translate.use();
                var preferredLanguage = $translate.preferredLanguage(); // we know we have set a preferred one in app.config
                $scope.language.selected = (proposedLanguage || preferredLanguage);
            },
            set: function (localeId, ev) {
                // Set the new idiom
                $translate.use(localeId);
                // save a reference for the current language
                $scope.language.selected = localeId;
                
                tmhDynamicLocale.set(localeId);
                
                i18nService.setCurrentLang(localeId);
                
                $rootScope.app.user.name = $rootScope.app.user[localeId + 'name'];
            }
        };

        $scope.language.init();

        // Restore application classes state
        toggle.restoreState( $(document.body) );

        // cancel click event easily
        $rootScope.cancel = function($event) {
            $event.stopPropagation();
        };
        
//==============================================sidebar====================================================
        // Hides/show user avatar on sidebar
        $scope.userBlockVisible = true;
        
        $scope.toggleUserBlock = function(){
            $scope.userBlockVisible = !$scope.userBlockVisible;
        };
        
        //menus
        var collapseList = [];

        // demo: when switch from collapse to hover, close all items
        $rootScope.$watch('app.layout.asideHover', function(oldVal, newVal){
            if (newVal === false && oldVal === true) {
                closeAllBut(-1);
            }
        });

        // Check item and children active state
        var isActive = function(item) {
            if (!item) return;

            if (!item.sref || item.sref == '#') {
                var foundActive = false;
                angular.forEach(item.children, function(value, key) {
                    if (isActive(value)) foundActive = true;
                });
                return foundActive;
            }else
                return $state.is(item.sref) || $state.includes(item.sref);
        };

        // Load menu
        $scope.getMenuItemPropClasses = function(item) {
            return (item.is_head == 1 ? 'nav-heading' : '') +
                    (isActive(item) ? ' active' : '') ;
        };

        $scope.loadSidebarMenu = function() {
            var promise = httpUtils.promise('/sysMenu/getUserMenus');
            promise.then(function(result) {
                var datas = result.data.datas;
                $scope.menuItems = datas;
                var firstMenu, hasFirst = false, 
                    stateToGo = $rootScope.stateToGo, isStateToGoValid = false, 
                    userMenus = {},
                    userMenusByID = {};

                var addMenu = function(menu){   
                    userMenusByID["id_" + menu.tid] = menu;
                    if (utils.isEmpty(menu.children)){        
                        userMenus[menu.sref] = menu;
                        
                        if (!utils.isEmpty(stateToGo) && !isStateToGoValid && menu.sref === stateToGo){
                            isStateToGoValid = true;
                        }
                    
                        if (!hasFirst && !utils.isEmpty(menu.sref)){
                            //记录第一个菜单
                            firstMenu = menu.sref;
                            hasFirst = true;
                        }
                    }else {
                        for (var j = 0; j < menu.children.length; j++){
                            addMenu(menu.children[j]);
                        }
                    }
                }
                for (var i = 0; i < datas.length; i++){
                    addMenu(datas[i]);
                }
                
                $scope.userMenus = userMenus;
                $scope.userMenusByID = userMenusByID;
                
                if ($state.current.name == 'app.loading'){
                    if (isStateToGoValid){
                        //从url进入 但由于没登陆 跳转到登录页面
                        $state.go(stateToGo);
                        $rootScope.stateToGo = '-1';
                    }else {
                        //从登录页进入
                        $state.go(firstMenu);
                    }
                }else{
                    //已登录状态 刷新url
                    setCurrentTitle($state.current.name);
                }
            }, function(datas) {  // 错误回调
                console.log('请求失败');
            }); 
        };
        
        var setCurrentTitle = function(stateName){
            var currentMenu = $scope.userMenus[stateName],
                currentTitle = $translate.instant(currentMenu.translate) || currentMenu.label,
                parentMenu = $scope.userMenusByID["id_" + currentMenu.parent_id];
            if(!utils.isEmpty(parentMenu)){
                currentTitle = ($translate.instant(parentMenu.translate) || parentMenu.label) + ' -> ' + currentTitle;
                var grandparentMenu = $scope.userMenusByID["id_" + parentMenu.parent_id];
                if(!utils.isEmpty(grandparentMenu)){
                    currentTitle = ($translate.instant(grandparentMenu.translate) || grandparentMenu.label) + ' -> ' + currentTitle;
                }
            }
            
            $scope.currentTitle = currentTitle;
        }
        
        $scope.loadSidebarMenu();

        // Handle sidebar collapse items
        // ----------------------------------- 

        $scope.addCollapse = function($index, item) {
            collapseList[$index] = $rootScope.app.layout.asideHover ? true : !isActive(item);
        };

        $scope.isCollapse = function($index) {
            return (collapseList[$index]);
        };

        $scope.toggleCollapse = function($index, isParentItem) {
            // collapsed sidebar doesn't toggle drodopwn
            if( utils.isSidebarCollapsed() || $rootScope.app.layout.asideHover ) return true;

            // make sure the item index exists
            if(angular.isDefined(collapseList[$index])) {
                if (!$scope.lastEventFromChild) {
                    collapseList[$index] = !collapseList[$index];
                    closeAllBut($index);
                }
            } else if (isParentItem) {
                closeAllBut(-1);
            }
            
            $scope.lastEventFromChild = isChild($index);

            return true;
        };

        function closeAllBut(index) {
            index += '';
            for(var i in collapseList) {
                if(index < 0 || index.indexOf(i) < 0)
                    collapseList[i] = true;
            }
        }

        function isChild($index) {
            return (typeof $index === 'string') && !($index.indexOf('-') < 0);
        }
        
//==============================================top-navbar====================================================
        $scope.logout = function(){
            httpUtils.post('/logout',{},
                function(result) {
                    $rootScope.app.user = {};
                    $rootScope.app.isSessionValid = false;
                    $scope.userMenus = [];
                    $state.go('page.login');
                }
            );
        }

        $scope.replacePassword = function(){
            ngDialog.openConfirm({
                plain: true,
                template: '\
                    <div class="ngdialog-message">\
                        <h5>新密码</h5>\
                        <p><input ng-model="password"/></p>\
                        <div class="ngdialog-buttons">\
                            <button type="button" class="ngdialog-button ngdialog-button-secondary" ng-click="closeThisDialog()">取消</button>\
                            <button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="confirm(password)">确定</button>\
                        </div>\
                    </div>\
                '
            }).then(function (password) {
                httpUtils.post('/sysUser/replacePassword',{password: password},
                    function(result){
                        if (result.success){
                            toaster.pop('success', '', '修改成功');
                        }else{
                            toaster.pop('error', '', result.msg);
                        }
                    },
                    function(result){
                        toaster.pop('error', '', '修改失败');
                    }
                );
            });
        }
    }
]);
